package org.groupg.project;

import org.pcollections.*;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.stream.Collectors;

public class PCollectionsDemo {

    public static void main(String[] args) {
        // 1. 持久化向量（List）
        PVector<String> baseVector = TreePVector.from(Arrays.asList("A", "B", "C"));

        PVector<String> v1 = baseVector.plus("D");
        PVector<String> v2 = baseVector.plus("E");

        System.out.println("基础向量: " + baseVector);
        System.out.println("版本1: " + v1);
        System.out.println("版本2: " + v2);

        // 2. 持久化映射（Map）
        PMap<String, Integer> baseMap = HashTreePMap.from(
            Map.of("Apple", 3, "Banana", 5));

        PMap<String, Integer> mapV1 = baseMap.plus("Orange", 2);
        PMap<String, Integer> mapV2 = baseMap.minus("Banana");

        System.out.println("\n基础映射: " + baseMap);
        System.out.println("添加Orange: " + mapV1);
        System.out.println("移除Banana: " + mapV2);

        // 3. 持久化Set
        PSet<String> baseSet = HashTreePSet.from(Set.of("Red", "Green", "Blue"));

        PSet<String> setV1 = baseSet.plus("Yellow");
        PSet<String> setV2 = baseSet.minus("Green");

        System.out.println("\n基础Set: " + baseSet);
        System.out.println("添加Yellow: " + setV1);
        System.out.println("移除Green: " + setV2);

        // 4. 结构共享演示
        PVector<String> sharedBase = TreePVector.empty();
        PVector<String> v100 = sharedBase.plusAll(Arrays.asList("A", "B", "C", "D", "E"));
        PVector<String> v101 = v100.with(2, "X");
        PVector<String> v102 = v100.with(4, "Z");

        System.out.println("\n结构共享演示:");
        System.out.println("v100: " + v100);
        System.out.println("v101: " + v101);
        System.out.println("v102: " + v102);

        // 5. 历史版本管理
        PStack<PVector<String>> history = ConsPStack.empty();
        PVector<String> current = TreePVector.empty();

        // 添加操作记录
        history = history.plus(current);
        current = current.plus("Step1");

        history = history.plus(current);
        current = current.plus("Step2");

        history = history.plus(current);
        current = current.plus("Step3");

        System.out.println("\n当前状态: " + current);

        // 回滚到上一步
        current = history.get(history.size() - 2);
        System.out.println("回滚后: " + current);

        // 6. 持久化集合的性能优势
        int size = 10000;
        PVector<Integer> bigVector = TreePVector.empty();

        long start = System.currentTimeMillis();
        for (int i = 0; i < size; i++) {
            bigVector = bigVector.plus(i);
        }
        long duration = System.currentTimeMillis() - start;

        System.out.println("\n创建" + size + "元素的持久化向量耗时: " + duration + "ms");
        System.out.println("前5个元素: " + bigVector.stream().limit(5).toList());
    }
}